package cn.zswltech.gruul.auth;

import cn.zswltech.gruul.biz.service.LoginService;
import cn.zswltech.gruul.common.constant.SystemConstant;
import cn.zswltech.gruul.common.entity.DisplayMenuTreeDO;
import cn.zswltech.gruul.common.entity.UserDO;
import cn.zswltech.gruul.common.result.MSG;
import cn.zswltech.gruul.common.result.Response;
import cn.zswltech.gruul.domain.entity.CheckResult;
import cn.zswltech.gruul.web.api.util.CookieUtils;
import cn.zswltech.gruul.web.api.util.JwtUtils;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerMapping;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
 * @author Jim
 * @version 1.0.0
 * @descripition:
 * @date 2024/2/2 10:40
 */
@Service
@Slf4j
public class ThirdApplicationAuthChecker extends AbstractAuthChecker{

    @Resource(name = "loginService")
    private LoginService loginService;

    @Override
    public Boolean check(HttpServletRequest request, HttpServletResponse response, Object handler) {
        // 测试账户不校验权限
        if (testAccount(request)){
            return true;
        }
        String sjToken = CookieUtils.getSJToken(request);

        // 访问路径
        String servletPath = (String) request.getAttribute(HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE);
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }


        String method = request.getMethod();
        if (StringUtils.isEmpty(sjToken)) {
            log.info("token验证失败");
            return false;
        }

        //验证JWT的签名，返回CheckResult对象
        JSONObject jsonObject = JSONObject.parseObject(sjToken);
        String salt = jsonObject.getString(CookieUtils.WL_TOKEN);
        CheckResult checkResult = JwtUtils.validateJWT(salt);
        if (!checkResult.isSuccess()) {
            switch (checkResult.getErrCode()) {
                // 签名验证不通过
                case SystemConstant.JWT_ERRCODE_FAIL:
                    log.info("签名验证不通过");
                    print(response, Response.error(MSG.req_error_sign_not_pass), HttpStatus.UNAUTHORIZED.value());
                    break;
                // 签名过期，返回过期提示码
                case SystemConstant.JWT_ERRCODE_EXPIRE:
                    log.info("签名过期");
                    print(response, Response.error(MSG.req_error_sign_expire), HttpStatus.UNAUTHORIZED.value());
                    break;
                default:
                    break;
            }
            return false;
        }

        // 账号
        String account = (String) checkResult.getClaims().get("sub");
        //pwd
        String pwd = (String) checkResult.getClaims().get("jti");
        // 检查用户是否存在,唯一登录校验
        UserDO userDO = new UserDO();
        userDO.setAccount(account);
        userDO.setPwd(pwd);
        Response res = loginService.checkUser(userDO, response);
        if (!res.isSuccess()) {
            int httpCode = HttpStatus.UNAUTHORIZED.value();

            print(response, res, httpCode);
            return false;
        }
        return true;
    }

    private boolean testAccount(HttpServletRequest request) {
        String testAccount = request.getHeader("test-account");
        if (testAccount != null && testAccount.equals("xupeng")){
            return true;
        }
        return false;
    }


}
